<?php

namespace App\Tools;

class UploadSlicesFile
{
    private $file, $now_slices, $total_size, $total_slices, $ext_arr, $file_name, $result_data, $ext;
    private $file_save_path = 'storage/uploads/';
    public function __construct($file, $path, $now_slices, $total_slices, $total_size, $ext_arr = [])
    {
        $this->file = $file;
        $this->total_size = $total_size;
        $this->total_slices = $total_slices;
        $this->ext_arr = $ext_arr;
        $this->file_save_path = $this->file_save_path . $path;
        $this->now_slices = $now_slices;

        $save = $this->upload();
        if (!$save) {
            $this->result_data = result_json(409, '上传失败');
            return;
        }
        $merge = $this->merge();
        $this->result_data = $merge;
        return;
    }

    /**
     * 返回上传结果
     * @return bool
     */
    public function getResultData()
    {
        return $this->result_data;
    }

    /**
     * 上传文件
     * @return array|bool|string
     */
    private function upload()
    {
        if (!$this->file->isValid()) return result_json(409, '文件无效');
        $client_name = $this->file->getClientOriginalName();
        $this->file_name = substr($client_name, 0, strrpos($client_name, "."));
        $size = $this->file->getSize();
        $ext = $this->file->getClientOriginalExtension();
        $this->ext = '.' . $ext;
        if (!in_array($ext, $this->ext_arr)) return result_json(409, '文件格式为apk, ipa');
        if($size > 200*1024*1024) return result_json(409, '文件大小不能超过200M');

        $new_wame = $this->file_name . '_' . $this->now_slices . "." . $ext;
        $path = $this->file->move($this->file_save_path, $new_wame);
        if(!$path) return false;
        return true;
    }

    /**
     * 合并文件
     * @return bool
     */
    private function merge()
    {
        if ($this->now_slices < $this->total_slices) return result_json(200, '继续上传', ['is_last' => false]);
        $file = '';
        for ($i = 1; $i <= $this->total_slices; $i++) {
            $file .= file_get_contents($this->file_save_path . $this->file_name . '_' . $i . $this->ext);
        }
        file_put_contents($this->file_save_path . $this->file_name . $this->ext, $file);
        $file_path = $this->file_save_path . $this->file_name . $this->ext;
        if (!is_file($file_path)) return result_json(409, '上传失败');
        $this->delete();
        return result_json(200, '成功', ['is_last' => true, 'file_path' => $file_path, 'file_size' => $this->getfileSize()]);
    }

    /**
     * 删除临时切片
     */
    private function delete()
    {
        for ($i = 1; $i <= $this->total_slices; $i++) {
            @unlink($this->file_save_path . $this->file_name . '_' . $i . $this->ext);
        }
    }

    /**
     * 获取文件大小
     * @param $path
     * @param string $type
     * @return string
     */
    private function getfileSize($type = 'M')
    {
        $size = round($this->total_size / 1024 / 1024, 2) . $type;
        return $size;
    }
}
